"""
进程池使用示例
CPU密集型使用
"""
import random
import time
from concurrent.futures import ProcessPoolExecutor, Future

# 创建一个有5个工作线程的进程池
pool = ProcessPoolExecutor(max_workers=5)
# 任务列表
task_list = ["task1", "task2", "task3", "task4", "task5", "task6", "task7", "task8", "task9", "task10"]


# 任务处理方法
def handler(task_name: str) -> str:
    # 构建随机数
    n = random.randrange(5)
    time.sleep(n)
    print(f"任务内容:{task_name}")
    return task_name


# 线程回调函数
def done(response: Future):
    print("done拿到的返回值:", response.result())


if __name__ == "__main__":
    for task in task_list:
        future = pool.submit(handler, task)
        future.add_done_callback(done)
    # 等待进程池内线程任务执行完
    pool.shutdown()
    print("main方法执行完毕")

